package com.smallrig.extension.ext;

import com.smallrig.extension.ExtensionException;
import com.smallrig.extension.dto.BizSceneWrapper;
import com.smallrig.extension.ExtensionSpi;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class ExtensionRepository {

    //接口名字，场景，spi
    private Map<String,Map<BizSceneWrapper,ExtensionSpi>> extensionRepo = new HashMap<>();

    private static final String EXTENSION_DEFINE_DUPLICATE = "extension_define_duplicate";


    public void put(String key,BizSceneWrapper wrapper,ExtensionSpi spi){
        extensionRepo.compute(key,(k,v)->{
            if(null==v){
                v = new HashMap<>();
            }
            ExtensionSpi oldSpi = v.put(wrapper, spi);
            if (oldSpi != null) {
                String errMessage = "Duplicate registration is not allowed for :" + wrapper;
                throw new ExtensionException(EXTENSION_DEFINE_DUPLICATE, errMessage);
            }
            return v;
        });
    }

    public ExtensionSpi get(BizSceneWrapper wrapper){
        return extensionRepo.get(wrapper.getExtensionName()).get(wrapper);
    }

    public Map<BizSceneWrapper,ExtensionSpi> get(String className){
        return extensionRepo.get(className);
    }


}
